package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import javax.swing.JFrame;
import protocolo.Login;
import protocolo.Mensagem;
import rede.Cliente;
import protocolo.ExisteLoginException;
import rede.MostraDados;

/**
 * @author tiagosn
 */
public class JanelaChat extends JFrame implements MostraDados {
    private Cliente<JanelaChat> cliente;
    private String              login;

    public JanelaChat(String login, String ipServidor, int porta) throws UnknownHostException, IOException, ClassNotFoundException, ExisteLoginException {
        initComponents();
        this.login = login;
        cliente = new Cliente<JanelaChat>(this, new Login(this.login), ipServidor, porta);

        addWindowListener(
            new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent evt) {
                    sair();
                }
            }
        );
        jTAEscreverMensagem.addKeyListener(
            new KeyAdapter() {
                @Override
                public void keyPressed(KeyEvent e) { /// enviar a msg
                    int key = e.getKeyCode();
                    if (key == KeyEvent.VK_ENTER){
                        cliente.enviarMensagem(new Mensagem(getLogin(), jTAEscreverMensagem.getText()));
                        jTAEscreverMensagem.setText("");
                    }
                }

                @Override
                public void keyReleased(KeyEvent e) { /// apagar a caixa
                    int key = e.getKeyCode();
                    if (key == KeyEvent.VK_ENTER){
                        jTAEscreverMensagem.setText("");
                    }
                }
            }
        );
        jMISair.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    sair();
                }
            }
        );
        jBEnviar.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent e){
                    cliente.enviarMensagem(new Mensagem(getLogin(), jTAEscreverMensagem.getText()));
                    jTAEscreverMensagem.setText("");
                    jTAEscreverMensagem.requestFocus();
                }
            }
        );
    }

    public void mostrarMensagem(Mensagem mensagem) {
        jTAListaMensagens.append(mensagem.getLogin() + ": " + mensagem.getTexto() + '\n');
        setVisible(true);
    }

    public void atualizarListaUsuarios(ArrayList<String> logins) {
        jLUsuarios.setListData(logins.toArray());
    }

    private String getLogin(){
        return login;
    }

    private void desconectar(){
        cliente.terminarConexao();
    }

    private void sair(){
        desconectar();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTAListaMensagens = new javax.swing.JTextArea();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTAEscreverMensagem = new javax.swing.JTextArea();
        jBEnviar = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        jLUsuarios = new javax.swing.JList();
        jMBOpcoes = new javax.swing.JMenuBar();
        jMChat = new javax.swing.JMenu();
        jMISair = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Chat - jLocalChat");
        setMinimumSize(new java.awt.Dimension(626, 390));

        jTAListaMensagens.setColumns(20);
        jTAListaMensagens.setEditable(false);
        jTAListaMensagens.setLineWrap(true);
        jTAListaMensagens.setRows(5);
        jScrollPane2.setViewportView(jTAListaMensagens);

        jTAEscreverMensagem.setColumns(20);
        jTAEscreverMensagem.setLineWrap(true);
        jTAEscreverMensagem.setRows(5);
        jScrollPane1.setViewportView(jTAEscreverMensagem);

        jBEnviar.setText("Enviar");

        jScrollPane3.setViewportView(jLUsuarios);

        jMChat.setText("Chat");

        jMISair.setText("Sair");
        jMChat.add(jMISair);

        jMBOpcoes.add(jMChat);

        setJMenuBar(jMBOpcoes);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 288, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jBEnviar, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 343, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jBEnviar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane1))))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBEnviar;
    private javax.swing.JList jLUsuarios;
    private javax.swing.JMenuBar jMBOpcoes;
    private javax.swing.JMenu jMChat;
    private javax.swing.JMenuItem jMISair;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTAEscreverMensagem;
    private javax.swing.JTextArea jTAListaMensagens;
    // End of variables declaration//GEN-END:variables
}
